﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using System.Net;
using System.Text.Json;

namespace MYData.WebApi.Exceptionfilter
{
    /*全局异常处理的作用*/
    /*避免在Controller或是Servervice或是项目中频繁的使用 try catch*/
    /*统一封装全局异常的返回格式
    第一步:定义返回格式
    第二步：定义自定义中间件
    第三步：应用中间件
     */
    public static class GlobalExceptionFilter
    {    
        public static void UseGlobalExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.ContentType = "application/json";

                    var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
                    if (errorFeature != null)
                    {
                        await context.Response.WriteAsync(new ErrorResponse
                        {
                            StatusCode = (HttpStatusCode)context.Response.StatusCode,
                            Message = $"错误信息是:{errorFeature.Error.Message},发生错误的地址:{context.Request.Host + context.Request.Path}"
                        }.ToJsonString());
                    }
                });
            });
        }

        public static void UseGlobalExceptionHandler(this IApplicationBuilder app, bool can)
        {
            if (can)
            {
                app.UseExceptionHandler(appError =>
                {
                    appError.Run(async context =>
                    {
                        context.Response.ContentType = "application/json";

                        var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
                        if (errorFeature != null)
                        {
                            await context.Response.WriteAsync(new ErrorResponse
                            {
                                StatusCode = (HttpStatusCode)context.Response.StatusCode,
                                Message = errorFeature.Error.Message
                            }.ToJsonString());
                        }
                    });
                });
            }
            else
            {
                return;
            }
        }
    }
}
